package cn.singno.bob.web.security;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import cn.singno.bob.common.utils.RandomUtil;

/**
 * csrf token管理器
 * @author 鲍建明
 *
 */
public class CsrfTokenManager {
	
	/*public static final String CSRF_PARAM_NAME = "csrfToken";
	public static final String CSRF_TOKEN_FOR_SESSION_ATTR_NAME = CsrfTokenManager.class
			.getName() + ".tokenval";
	
	private org.springframework.cache.CacheManager CacheManager;
	
	private String scrfCacheName;
	
	
	public void setCacheManager(org.springframework.cache.CacheManager cacheManager) {
		CacheManager = cacheManager;
	}


	public String createTokenForSession(HttpServletRequest request) {
		String token = null;
		synchronized (request) {
			
			String csrfCookieId = CookieUtils.get(request, CSRF_TOKEN_FOR_SESSION_ATTR_NAME);
			if(StringUtils.isNotBlank(csrfCookieId)){
				Cache csrfCache = CacheManager.getCache(scrfCacheName);
				String csrfToken = csrfCache.get(csrfCookieId, String.class);
				if(StringUtils.isBlank(csrfToken)){
					csrfToken = RandomUtil.buildUUID();
					csrfCache.put(csrfCookieId, csrfToken);
				}
				return csrfToken;
				
			}else{
				String csrfToken = RandomUtil.buildUUID();
				csrfCookieId = "hengxin_sessionId_" + csrfToken;
				CookieUtils.put(response, request, key, value);
				Cache csrfCache = CacheManager.getCache(scrfCacheName);
				csrfCache.put(csrfCookieId, csrfToken);
			}
			
		}
		
		return token;
	}*/
	
	
	
	

	// 隐藏域参数名称
	public static final String CSRF_PARAM_NAME = "csrfToken";

	// session中csrfToken参数名称
	public static final String CSRF_TOKEN_FOR_SESSION_ATTR_NAME = CsrfTokenManager.class
			.getName() + ".tokenval";

	private CsrfTokenManager() {
	};

	// 在session中创建csrfToken
	public static String createTokenForSession(HttpSession session) {
		String token = null;
		synchronized (session) {
			token = (String) session
					.getAttribute(CSRF_TOKEN_FOR_SESSION_ATTR_NAME);
			if (null == token) {
				token = RandomUtil.buildUUID();
				session.setAttribute(CSRF_TOKEN_FOR_SESSION_ATTR_NAME, token);
			}
		}
		return token;
	}

	public static String getTokenFromRequest(HttpServletRequest request) {
		return request.getParameter(CSRF_PARAM_NAME);
	}
}
